package com.llt.user.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.llt.annotation.UserLoginToken;
import com.llt.enum_util.ResponseBodyEnum;
import com.llt.pojo.common.AjaxResponseBody;
import com.llt.user.entity.User;
import com.llt.user.mapper.UserMapper;
import com.llt.utils.RedisUtil;
import com.llt.utils.Utils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author llt
 * @since 2020-12-10
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(value = "用户注册",tags = {"用户注册"})
public class UserController {
        @Autowired
        private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
        @PostMapping("/signIn")
        @ResponseBody//将java对象转为json格式的数据。
                @ApiImplicitParams(
                {

                @ApiImplicitParam( name = "email", value = "用户的email", required = true, dataType="String"  ),
                @ApiImplicitParam(  name = "password", value = "用户的密码", required = true, dataType="String"),
                @ApiImplicitParam(    name = "code", value = "验证码", required = true, dataType="String"  )
                }   )
        @ApiOperation(value = "用户登录",response = User.class,notes="密码与验证码有一个即可")
        public AjaxResponseBody signIn(@RequestBody @Validated  User user, HttpServletResponse httpServletResponse){

                if (user.getPassword()!="" &&user.getCode()!=""){
                   //捣乱的
                    return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_OTHER);
                }else if (user.getPassword()!=""){
                    //走密码
                    HashMap<String, Object> keys = new HashMap<>();
                    keys.put("password",Utils.getMd5_2(user.getPassword()));
                    keys.put("email",user.getEmail());
                    List<User> users = userMapper.selectByMap(keys);
                    if (users.size()==0){
                        //邮箱或密码不正确
                        return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_USER_LOGIN_ERROR);
                    }
                    //邮箱密码正确 返回token 用户信息
                    long time  =7* 60 * 60 * 1000;//7小时
                    String token = Utils.getToken(user.getEmail(),time);
                    //成功
                    Cookie cookie = new Cookie("token",token);
                    httpServletResponse.addCookie(cookie);
                    return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK,users,token);
                }else if (user.getCode()!=""){
                    //走验证码
                    /**
                     * 1 对比验证码
                     *      1 一样 通过验证返回token
                     *      2 不一样 删除redis验证码 返回登录错误提示
                     */
                    if (!redisUtil.hasKey(user.getEmail()))return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_TIMEOUT);//如果没有返回超时提醒
                    //校验验证码是否匹配
                    String codeString =(String) redisUtil.get(user.getEmail());//获取redis 服务器的验证码对比
                    if (!codeString.equalsIgnoreCase(user.getCode())) return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_NO_LIKE);//验证码不一样
                    //通过验证码 注册用户
                    HashMap<String, Object> keys = new HashMap<>();
                    keys.put("email", user.getEmail());
                    List<User> users = userMapper.selectByMap(keys);
                    if(users.size()==0){
                        //因为每用户所以添加用户 如果不等于0 说明有就不添加了
                        int register = userMapper.insert(user);
                        if (register!=1){
                            return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_SYSTEM_ERROR);
                        }
                    }
                    //邮箱密码正确 返回token 用户信息
                    long time  =7* 60 * 60 * 1001;//7小时
                    String token = Utils.getToken(user.getEmail(),time);
                    //成功
                    Cookie cookie = new Cookie("token",token);
                    httpServletResponse.addCookie(cookie);
                    return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK,users,token);

                }
            return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_OTHER);
        }

        @PostMapping("/registerUser")
        @ResponseBody
        @ApiImplicitParams(
                {
                        @ApiImplicitParam(name = "username", value = "用户的名字", required = true, dataType="String" ),
                        @ApiImplicitParam( name = "email", value = "用户的email", required = true, dataType="String"  ),
                        @ApiImplicitParam(  name = "password", value = "用户的密码", required = true, dataType="String"),
                        @ApiImplicitParam(  name = "sex", value = "用户的性别", required = true, dataType="String"),
                        @ApiImplicitParam(    name = "code", value = "验证码", required = true, dataType="String"  )
                }   )
        @ApiOperation(value = "用户注册",response = User.class,notes="用户注册账户的")
        public AjaxResponseBody registerUser( @RequestBody @Validated  User user) {
            if (!redisUtil.hasKey(user.getEmail()))return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_TIMEOUT);//如果没有返回超时提醒
            //校验验证码是否匹配
            String codeString =(String) redisUtil.get(user.getEmail());//获取redis 服务器的验证码对比
            if (!codeString.equalsIgnoreCase(user.getCode())) return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_NO_LIKE);//验证码不一样
            if (user.getPassword() != "" && user.getCode() != "" && user.getEmail() != "" && user.getSex() != null && user.getUsername() != "") {
                        //查询是否有存在的 邮箱
                        HashMap<String, Object> keys = new HashMap<>();
                        keys.put("email", user.getEmail());
                        List<User> users = userMapper.selectByMap(keys);
                        if (users.size() >0) {
                            User user1 = users.get(0);
                            if (user1.getUsername()==null){
                                //说明之前是邮箱注册 更新字段
                                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                                updateWrapper.eq("email",user.getEmail())
                                        .set("password",Utils.getMd5_2(user.getPassword()))
                                        .set("username",user.getUsername())
                                        .set("sex",user.getSex())
                                        .set("age",user.getAge())
                                        .set("job",user.getJob())
                                        .set("address",user.getAddress())
                                        .set("mobile",user.getMobile())

                                ;
                                 userMapper.update(null, updateWrapper);
                                return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK);
                            }else {
                                //已经注册过了无法注册
                                return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_EMAIL_FIND);
                            }

                        }
                        //没有纯在的邮箱即添加用户
                        user.setPassword(Utils.getMd5_2(user.getPassword()));
                        int insertStatus = userMapper.insert(user);
                        if (insertStatus!=1){
                                return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_SYSTEM_ERROR);
                        }
                        return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK);

             } else {
                        //捣乱的
                        return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_OTHER);
              }


        }

    @GetMapping("/resetPassword")
    @ApiOperation(value = "重置验证码")
    public AjaxResponseBody geteMailCode(@ApiParam (value = "email",name = "邮箱",required = true) String email,
    @ApiParam (value = "code",name = "验证码",required = true) String code,
     @ApiParam (value = "newPassword",name = "新密码",required = true) String newPassword
    ){
        if (email == "" || code =="" || newPassword=="") return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_OTHER);
        if (!redisUtil.hasKey(email))return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_TIMEOUT);//如果没有返回超时提醒
        //校验验证码是否匹配
        String codeString =(String) redisUtil.get(email);//获取redis 服务器的验证码对比
        if (!codeString.equalsIgnoreCase(code)) return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_CODE_NO_LIKE);//验证码不一样
        // 更换密码
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("email",email).set("password",Utils.getMd5_2(newPassword));
        int update = userMapper.update(null, updateWrapper);
        if (update!=1){
            //更新错误
            return new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_SYSTEM_ERROR);
        }
        //重置成功
        return  new AjaxResponseBody(ResponseBodyEnum.RESPONSE_BODY_ENUM_OK);
    }
}

